package view;

import dao.IPessoaDAO;
import dao.PessoaDAOTXT;
import factoryDinamico.TipoDAOFactory;
import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.beans.PropertyVetoException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JInternalFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import presenter.InclusaoPessoaPresenter;
import presenter.ListaPessoasPresenter;
import javax.swing.JOptionPane;
import model.Pessoa;

public final class Main extends javax.swing.JFrame {

    IPessoaDAO<Pessoa> pessoas;

    /**
     * Creates new form Main
     * @throws java.io.FileNotFoundException
     */
    public Main() throws FileNotFoundException, IOException, Exception {
        initComponents();
        this.setLocationRelativeTo(this.getParent());
        this.setExtendedState(MAXIMIZED_BOTH);
        pessoas = carregaDAO();
    }

    public IPessoaDAO carregaDAO() throws Exception {
        IPessoaDAO<Pessoa> classeDAO = null;
        try {
            //classeDAO = PessoaDAOTXT.getInstance();
            TipoDAOFactory.carregaDAO(); // para carregar o propertis e sei qual instacia tenho do DAO
            classeDAO = TipoDAOFactory.create("XML");
        } catch (FileNotFoundException e) {
            try {
                throw new Exception("Não foi possível carregar o DAO \n" + e.getMessage());
            } catch (Exception ex) {

                JOptionPane.showMessageDialog(this, ex.getMessage());
                System.exit(0);
            }
        }
        return classeDAO;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        desktop = new org.mdidesktoppane.MDIDeskTopPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cadastro de pessoas");

        jMenu1.setMnemonic('O');
        jMenu1.setText("Opções");
        jMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu1ActionPerformed(evt);
            }
        });

        jMenuItem1.setMnemonic('A');
        jMenuItem1.setText("Adicionar");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setMnemonic('L');
        jMenuItem2.setText("Listar pessoas");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem3.setMnemonic('S');
        jMenuItem3.setText("Sair");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktop, javax.swing.GroupLayout.DEFAULT_SIZE, 610, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktop, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenu1ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        InclusaoPessoaPresenter inclusaoPessoaController = new InclusaoPessoaPresenter(this.pessoas, null);
        try {
            activePanel(inclusaoPessoaController.getView(), false, false);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
        try {
            ListaPessoasPresenter listaPessoasController;
            listaPessoasController = new ListaPessoasPresenter(this.pessoas);
            pessoas.addObserver(listaPessoasController);
            activePanel(listaPessoasController.getView(), false, false);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
                    UIManager.setLookAndFeel(lookAndFeel);
                    new Main().setVisible(true);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public static void removeFrame(String name) {
        for (JInternalFrame frame : desktop.getAllFrames()) {
            if (frame.getClass().getCanonicalName().contains(name)) {
                frame.setVisible(false);
                frame.dispose();
                desktop.remove(frame);
                break;
            }
        }
    }

    public static void activePanel(JInternalFrame frame, Boolean maximize, Boolean closable) throws PropertyVetoException {
        if (closable) {
            desktop.add(frame);
        } else {
            if (!desktop.contain(frame)) {
                desktop.remove(frame);
                desktop.add(frame);
            }
        }
        // Muda de elemento ao pressionar ENTER
        HashSet conj = new HashSet(frame.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
        conj.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER, 0));
        frame.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, conj);

        frame.setIconifiable(true);
        frame.setIcon(true);
        frame.setVisible(true);
        frame.setClosable(closable);
        frame.setMaximizable(true);
        frame.setResizable(true);
        if (!maximize) {
            frame.setIcon(false);
        } else {
            frame.setMaximum(true);
        }
        frame.moveToFront();

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private static org.mdidesktoppane.MDIDeskTopPane desktop;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    // End of variables declaration//GEN-END:variables
}
